<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="auto">
            <EdCreateCard title="商品信息">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-row class="width-100">
                        <el-col :span="16">
                            <el-form-item label="商品名称" prop="productName" :rules="$validate.validates({required:true,msg:'不能为空',type: 'producetName'})">
                                <el-input class="flex-input" placeholder="请输入商品名称" v-model="form.productName" maxlength="50"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="16">
                            <el-form-item label="商品类别" prop="categoryId" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <!-- <EdSelect v-model="form.categoryId" :selectParams="selectGoodsType"></EdSelect> -->
                                <EdCascader v-model="form.categoryId" :cascaderParams="selectGoodsType"></EdCascader>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="8">
                            <el-form-item label="商品来源" prop="productSource" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <EdSelect v-model="form.productSource" :selectParams="selectSource"></EdSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="产品编号" prop="productNumber" :rules="$validate.validates({required:productNumber_require,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入产品编号" v-model="form.productNumber" maxlength="18"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="8">
                            <el-form-item label="商品限价" prop="productPrice" :rules="$validate.validates({required:true,msg:'不能为空', type: 'money'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.productPrice" maxlength="11">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">元</i>
                                </el-input>
                                <!-- <div v-show="form.productPrice&&form.productPrice<=0" style="font-size: 12px; color: #F56C6C;">必须为正数</div> -->
                                <!-- <div v-show="form.productPrice&&!( /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(form.productPrice))" style="font-size: 12px; color: #F56C6C;">请保留两位有效小数</div> -->
                                <!-- <div v-show="form.productPrice.length>0&&(!(regFloatTwo.test(form.productPrice))||form.productPrice==0)" style="font-size: 12px; color: #F56C6C;">必须为正数，且最多保留两位有效小数</div> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="是否支持退款" prop="refundStatus" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-radio-group v-model="form.refundStatus">
                                    <el-radio v-for="item in canRefundList" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                     <el-row class="width-100">
                        <el-col :span="8">
                           <!-- <el-form-item label="是否物业配送" prop="propertyStatus" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-radio-group v-model="form.propertyStatus">
                                    <el-radio v-for="item in canSendList" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item> -->
                              <el-form-item label="核销方式" prop="verification" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                    <EdSelect v-model="form.verification" :selectParams="selectVerifyMethod" @emit-select-value="handleVerificationChange"></EdSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="总库存" prop="productStock" :rules="$validate.validates({type: 'stock'})">
                                <el-input class="flex-input" v-model="form.productStock" maxlength="8">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">件</i>
                                </el-input>
                                <!-- <span v-show="form.productStock&&!(/^\d*$/.test(form.productStock))" style="color: #F56C6C;margin-left: 5px">请输入整数</span> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="8">
                            <el-form-item label="活动时间" prop="activityTime">
                                <!-- <EdDateTimeRange ref="timeRange" @emit-echo-time-range="emitEchoTimeDate($event, 'activityTime')"></EdDateTimeRange> -->
                                <EdDateTimePickerRange :pickerOptions="'days'" v-model="form.activityTime"  @emit-echo-time-range="emitEchoTimeDate($event, 'activityTime')" :pickerParams="pickerRangeParams"></EdDateTimePickerRange>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="24">
                            <el-form-item label="商品图片" prop="productPics" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-upload
                                    class="upload-img"
                                    accept="image/*"
                                    :action="action"
                                    list-type="picture-card"
                                    :limit="5"
                                    :multiple="true"
                                    :file-list="fileList"
                                    :before-upload="beforeImgUpload"
                                    :on-preview="handleImgPreview"
                                    :on-success="handleImgSuccess"
                                    :on-remove="handleImgRemove">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                            <p class="labelFont">请上传2M以内，大小430px*430px，格式为jpeg、jpg、png、gif的图片，至多5张</p>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="16">
                            <el-form-item label="商品详情" prop="descriptionType" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <!-- <el-input class="flex-input" v-model="form.descriptionType"></el-input> -->
                                <el-radio-group v-model="form.descriptionType" @change="handleDesChange">
                                    <el-radio v-for="item in goodsInfoList" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <el-form-item v-if="form.descriptionType==1" label="" prop="productUrl" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" v-model="form.productUrl" placeholder="请输入URL" maxlength="100"></el-input>
                            </el-form-item>
                            <el-form-item v-else label="" prop="description" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <EdTinymce ref="EdTinymce" v-model="form.description"></EdTinymce>
                                <!-- <EdTinymce v-if="form.descriptionType==2" ref="EdTinymce" v-model="form.description"></EdTinymce>
                                <el-input v-else class="flex-input" v-model="form.description" placeholder="请输入URL"></el-input> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item class="form_btns">
                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">确定</el-button>
                    <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router)">取消</el-button>
                </el-form-item>
            </EdCreateCard>
        </el-form>
    </div>
</template>

<script>
    import EdTinymce from 'src/components/EdTinymce.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdDateTimeRange from 'src/components/EdDateTimeRange.vue'
    import EdDateTimePickerRange from 'src/components/EdDateTimePickerRange.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import { defineComponent } from 'vue'
    import { resourceInfo, resourceAdd, resourceUpdate, getResourceType } from "./api";
    import { getDictByCode } from "src/api/dictionaries";
    export default defineComponent({
        name: "companyCreate",
        components: { EdCreateCard, EdDateTimeRange, EdSelect, EdTinymce, EdCascader, EdDateTimePickerRange },
        data(){
            return{
                form:{
                    productName: '',
                    categoryId: '',
                    productNumber: '',
                    productSource: '',
                    productPrice: '',
                    refundStatus: '1',
                    // propertyStatus: '0',
                    verification: '',
                    productStock: '',
                    activityTime: '',
                    activityStartTime: '',
                    activityEndTime: '',
                    productPics: [],
                    descriptionType: '2',
                    productUrl: '',
                    description: '',
                },
                pickerParams:{
                    valueFormat:"yyyy-MM-dd"
                },
                pickerRangeParams:{
                    valueFormat:"yyyy-MM-dd HH:mm"
                },
                disabled:false,
                isUpdate: false,
                fileList: [],
                action: '',
                dialogImageUrl: '',
                dialogVisible: false,
                selectGoodsType:{
                    placeholder:"请选择商品类别",
                    options: [],
                    props: { value: 'code', label: 'categoryName', checkStrictly: false, emitPath: false }
                },
                selectSource:{
                    placeholder:"请选择来源",
                    options: [],
                },
                selectVerifyMethod:{
                    placeholder:"请选择核销方式",
                    options: [],
                },
                canRefundList: [
                    { value: '1', label: '支持' },
                    { value: '0', label: '不支持' },
                ],
                canSendList: [
                    { value: '0', label: '否' },
                    { value: '1', label: '是' },
                ],
                goodsInfoList: [
                    { value: '1', label: '输入地址' },
                    { value: '2', label: '输入图文' },
                ],
                // 产品编号必填（来源为 卡券平台）
                productNumber_require: false,
                // 正数、两位有效小数校验
                regFloatTwo: /^(([1-9][0-9]{0,7})|([0]\.\d{1,2})|([1-9][0-9]{0,7}\.\d{1,2}))$/,
                uploadStyle: 'inline-block'
            }
        },
        activated(){
            getResourceType({ pageSize: 999999 }).then(res=>{
                this.selectGoodsType.options = res.data;
            })
            // 来源
            getDictByCode('product_source').then(res=>{
                this.selectSource.options = res.data.items;
            })
            // 核销方式
            getDictByCode('product_verify_method').then(res=>{
                this.selectVerifyMethod.options = res.data.items;
            })
            this.action = this.$baseApi + "/infra/file/upload";
            if(this.$route.query.id){
                // 编辑 
                this.isUpdate = true;
                this.resourceInfo();
            }else {
              
            }
        },
        deactivated(){
            this.form={
                productName: '',
                categoryId: '',
                productNumber: '',
                productSource: '',
                productPrice: '',
                refundStatus: '1',
                // propertyStatus: '0',
                verification: '',
                productStock: '',
                activityTime: '',
                activityStartTime: '',
                activityEndTime: '',
                productPics: [],
                descriptionType: '2',
                productUrl: '',
                description: '',
            }
            this.fileList = [];
            // this.$refs.timeRange.reset();
            // 清空editor的缓存
            if(this.$refs.EdTinymce) this.$refs.EdTinymce.$children[0].cache = '';
            this.productNumber_require = false;
            this.disabled = false;
            this.$refs.formRef.resetFields()
            this.uploadStyle = 'inline-block'
        },
        methods:{
            resourceInfo(){
                resourceInfo({id:this.$route.query.id}).then(response => {
                    if(response.success == true) {
                        this.form = {
                            id: response.data.id,
                            productName: response.data.productName,
                            categoryId: response.data.categoryId&&response.data.categoryId.toString(),
                            productNumber: response.data.productNumber,
                            productSource: response.data.productSource&&response.data.productSource.toString(),
                            productPrice: response.data.productPrice,
                            refundStatus: response.data.refundStatus.toString(),
                            // propertyStatus: response.data.propertyStatus.toString(),
                            verification: response.data.verification&&response.data.verification.toString(),
                            productStock: response.data.productStock,
                            activityStartTime: response.data.activityStartTime,
                            activityEndTime: response.data.activityEndTime,
                            activityTime: response.data.activityStartTime&&[response.data.activityStartTime, response.data.activityEndTime] || [],
                            productPics: response.data.productPics,
                            descriptionType: response.data.descriptionType&&response.data.descriptionType.toString(),
                            productUrl: response.data.productUrl,
                            description: response.data.description,
                        };
                        // 核销方式：卡券平台 -> 产品编号 必填
                        if(response.data.verification==1){
                            this.productNumber_require = true;
                        }else{
                            this.productNumber_require = false;
                        }
                        // this.$refs.timeRange.time = response.data.activityStartTime&&[response.data.activityStartTime, response.data.activityEndTime];
                        this.fileList = response.data.productPics.map(v=>{
                            return {url: v}
                        })
                    }
                })
            },
            emitEchoTimeDate($event, name){
                // $event 子组件$emit传的参数 
                // this.form['activityTime'] = $event;
                this.form['activityStartTime']=$event['startTime'];
                this.form['activityEndTime']=$event['endTime'];
            },
            onSubmit(formName){
                // 去空格
                this.form['productNumber']=this.form['productNumber']&&this.form['productNumber'].trim();
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        this.disabled = true;
                        let query = this.form.copy();
                        delete query['activityTime'];

                        // 限价：整数、两位小数
                        if(query.productPrice.length>0&&(!(this.regFloatTwo.test(query.productPrice))||query.productPrice==0)){
                            this.disabled = false
                            return this.$message.error({ message: '商品限价必须为正数，且最多保留两位有效小数！', center: true })
                        }
                        // console.log('query--->', query)
                        // return

                        if(query['descriptionType']==1){
                            query['description']='';
                        }else if(query['descriptionType']==2){
                            query['productUrl']='';
                        }
                        
                        let funcApi = this.isUpdate ? resourceUpdate : resourceAdd;
                        funcApi(query).then(response => {
                            if(response.success == true) {
                                this.disabled = false;
                                this.$message.success({
                                    message: '保存成功',
                                    center: true,
                                    duration: 2000,
                                });
                                if(this.$route.query.type !=0){
                                    window.setTimeout(() => {
                                        this.$utilsSet.goBack(this.$router);
                                    }, 600)
                                }
                            }else {
                                this.disabled = false
                            }
                        }).catch(()=>{
                            this.disabled = false
                        })
                    }
                })
            },
             // 图片 上传前
            beforeImgUpload(file){
                // console.log('before-->', file)
                // const fileType = file.name.split('.');
                // const fileDate = fileType.slice(-1);
                // if (['jpeg', 'jpg', 'png', 'gif'].indexOf(fileDate[0]) < 0) {
                // if (['jpeg', 'jpg', 'png', 'gif'].indexOf(file.type.split('/')[1]) < 0) {
                //     this.$message.error({message: '仅支持格式：jpeg、jpg、png、gif!', center: true});
                //     return false
                // }
                // if (this.fileList.length > 5) {
                //     this.$message.error('最多上传三张图片！')
                //     return false;
                // }
                const isLt5M = file.size / 1024 /1024 < 2;
                if (!isLt5M) {
                    this.$message.error({message: '上传文件大小不能超过 2MB!', center: true});
                }
                return isLt5M;
            },
            // 图片 上传成功
            handleImgSuccess(response, file, fileList){
                let res = file.response;
                if(res&&res.success == true){
                   this.form.productPics.push(res['data'])
                }
                this.uploadStyle = fileList.length==5?'none':'inline-block'
            },
            // 图片 删除
            handleImgRemove(file, fileList) {
                this.form.productPics = fileList&&fileList.map(v=>{
                    return v['response']? v['response']['data'] : v['url']
                })
                this.uploadStyle = fileList.length==5?'none':'inline-block'
            },
            // 图片 预览
            handleImgPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleDesChange(val){
                this.form.productUrl = '';
                this.form.description = '';
            },
            // 核销方式：卡券平台 -> 产品编号 必填
            handleVerificationChange(val){
                if(val==1){
                    this.productNumber_require = true;
                    // this.$set(this.form, 'propertyStatus', '0');
                }else{
                    this.productNumber_require = false;
                }
            }
        }
    })
</script>

<style scoped lang="scss">
    :deep {
        .el-form-item{
            .el-form-item__content{
                .el-input{
                    // width: 98% !important;
                    width: 100% !important;
                }
                .el-select{
                    width: 100% !important;
                    // width: 98% !important;
                    // .el-input{
                    //     width: 100% !important;
                    // }
                }
                 .el-cascader{
                    width: 100% !important;
                    // width: 98% !important;
                    // .el-input{
                    //     width: 100% !important;
                    // }
                }
                .el-date-editor{
                    width: 100% !important;
                    // width: 98% !important;
                }
                .el-radio-group .el-radio.is-checked{
                    .el-radio__input{
                        .el-radio__inner{
                            border-color: #EED096;
                            background: #EED096;
                        }
                    }
                    .el-radio__label{
                        color: #EED096;
                    }
                }

                .el-radio-group .el-radio{
                    .el-radio__input{
                        .el-radio__inner:hover{
                            border-color: #EED096;
                        }
                    }
                }
            }
        }

        .upload-img .el-upload{
            display: v-bind(uploadStyle)
        }
    }
    .img_center{
        display: flex;
        align-items: center;
    }
    .form_btns{
        // display: flex;
        // justify-content: flex-end;
        margin-left: 47px;
    }
    .labelFont{
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        color: #989898;
    }
</style>